
package com.ifcar.app.service;

import java.util.ArrayList;

import com.ifcar.app.activity.BaseActivity;
import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.activity.HomePage;
import com.ifcar.app.activity.SpecialAritcleTwo;
import com.ifcar.app.activity.newspage.NewsCommentFragment;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.AlarmUtil;
import com.ifcar.app.util.HttpUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

public class PushService extends Service {
    private static final String TAG = "PushService";

    public static final String KEY_AUTO_POST = "autopost";

    private static final String KEY_LAST_ID = "newestdocid";
    
    private static final int MSG_SHOW_NOTIFICATION = 0;

    private int push_interval = 60 * 1000;

    private static SharedPreferences mSP;

    private PowerManager.WakeLock mWakeLock;

    private NotificationManager mNotificationManager;

    private boolean mStarted;
    /*存储下次push间隔多长时间push*/
    public static String INTERVAL_TAG = "interval_tag";
    /*默认两分钟一次Push轮询*/
    public static int INTERVAL_LEVEL= 2 * 60 * 1000;
    /*存储上次push成功后的时间戳*/
    public static String GETLASTPUSH_TIME_TAG = "lastpush_time";
    /*两次push的超时时间间隔 TIMEOUT一定要 大于 INTERVAL_LEVEL*/
    public static  long TIMEOUT = 2 * 60 * 1000;
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        acquireWakeLock(this);
        mSP = PreferenceManager.getDefaultSharedPreferences(this);
        push_interval = mSP.getInt(INTERVAL_TAG, INTERVAL_LEVEL);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mStarted = false;
        if (needPush() && Tools.CheckNetwork(getApplicationContext())) {
            push_interval = mSP.getInt(INTERVAL_TAG, INTERVAL_LEVEL);
            startPushDelayed(getApplicationContext(), push_interval);
        }
        releaseWakeLock();
        
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        
        if (mStarted) {
            return;
        }
        mStarted = true;
        
        final String lastId = getLastPushId();
        new Thread() {
            @Override
            public void run() {
                doPush(lastId);
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        stopSelf();
                    }
                });
            }

        }.start();
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SHOW_NOTIFICATION:
                    showNotification((PushMsg) msg.obj);
                    return;
                default:
                    break;
            }
        }

    };
    
    private String getCurrentPushUrl(){
        long currenttime = System.currentTimeMillis();
        long _timeout = currenttime - getLastPushUrlTime();
        TIMEOUT = 10 * 1000 + mSP.getInt(INTERVAL_TAG, INTERVAL_LEVEL);
        if(_timeout>TIMEOUT){
            return StringUtil.LAST_PUSHURL;
        }else{
            return StringUtil.NOW_PUSHURL;
        }
    }
    
    private void setLastPushUrlTime(long time){
        mSP.edit().putLong(GETLASTPUSH_TIME_TAG, time).commit();
    }
    
    private long getLastPushUrlTime(){
        return mSP.getLong(GETLASTPUSH_TIME_TAG, 0);
    }
    
    private Intent getWhere(String id){
        
        if(TextUtils.isEmpty(id)){
            Intent intent = new Intent(this, HomePage.class);
            intent.putExtra("push", "push");
            intent.putExtra("pintent", "pintent");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(GetColumnsInfo.DOCID_TAG, "");
            intent.putExtra("position", "0");
            intent.putExtra(GetColumnsInfo.HEADLINE_TAG, true);
            return intent;
        }else{
            
            Intent intent = null;
            
            String[] arrayid = id.split("_");
            String realid = "";
            String type = "";
            if(arrayid.length>1){
                realid = arrayid[1];
                type = arrayid[0];
            }else{
                realid = arrayid[0];
            }
            
            if("doc".equals(type) || "odoc".equals(type)){//go文章
                
                intent = new Intent(this, NewsPage.class);
                intent.putExtra(NewsCommentFragment.PARAM_FOR_GO_MAIN, true);
                intent.putExtra("push", "push");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(GetColumnsInfo.DOCID_TAG, realid);
                intent.putExtra("position", "0");
                intent.putExtra(GetColumnsInfo.HEADLINE_TAG, true);
                
                if("odoc".equals(type)){//如果是奥运-文章
                    intent.putExtra(BaseActivity.PARAM_THEME, ThemeSettingsHelper.THEME_OLYMPIC);
                }
                
            }else if("spc".equals(type) || "ospc".equals(type)){//go专题
                
                intent = new Intent(this, SpecialAritcleTwo.class);
                intent.putExtra(NewsCommentFragment.PARAM_FOR_GO_MAIN, true);
                intent.putExtra("push", "push");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(GetColumnsInfo.SPECIAL_ID_TAG, realid);
                intent.putExtra("position", "0");
                intent.putExtra(GetColumnsInfo.HEADLINE_TAG, true);
                
                if("ospc".equals(type)){//如果是奥运-专题
                    intent.putExtra(BaseActivity.PARAM_THEME, ThemeSettingsHelper.THEME_OLYMPIC);
                }
                
            }else{//其他
                intent = new Intent(this, HomePage.class);
                intent.putExtra("push", "push");
                intent.putExtra("pintent", "pintent");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(GetColumnsInfo.DOCID_TAG, "");
                intent.putExtra("position", "0");
                intent.putExtra(GetColumnsInfo.HEADLINE_TAG, true);
            }
            
            return intent;
        }
    }
    
    /**
     * 等有了奥运push开关后再使用
     * @param id
     * @return
     */
    private boolean isOlympicPush(String id){
        if(TextUtils.isEmpty(id)){
            return false;
        }else{
            if(id.startsWith("odoc_") || id.startsWith("ospc_")){
                return true;
            }else{
                return false;
            }
        }
    }
    
    private void doPush(String lastId){
        
        if (!needPush()) {
            return;
        }
        String url = getCurrentPushUrl();
        //System.out.println("doPush url=" + url );
        String rst = HttpUtils.getResponseFromGetUrlForPUSH(url, 40 * 1000, this, mSP);
        //System.out.println("doPush rst=" + rst );
        if ("error".equals(rst)) {
            return;
        }
        //此返回结果是针对增量获取push结果是无消息，但是push是成功的
        if ("304".equals(rst)) {
            setLastPushUrlTime(System.currentTimeMillis());
            return;
        }
        JSONArray jsonarray = Tools.StringToJsonArray(rst);
        if (null == jsonarray) {
            return;
        }
        try {
            ArrayList<PushMsg> needList = getNeedMsg(jsonarray,lastId);

            final int count = needList.size() - 1;
            for(int index = 0;index <= count;index++){

                Message msg = mHandler.obtainMessage(MSG_SHOW_NOTIFICATION);
                msg.obj = needList.get(index);
                mHandler.sendMessage(msg);
                
                if (index != count) {
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException e) {
                    }
                }
                

            }
           
        } catch (Exception e) {
            
        }
    }
    
    private ArrayList<PushMsg> getNeedMsg(JSONArray jsonarray,String lastId){
        
        ArrayList<PushMsg> needList = new ArrayList<PushMsg>();
        
        try {
            if (null != jsonarray && jsonarray.length() > 0) {
               
                //成功后修改之后一次Push时间
                setLastPushUrlTime(System.currentTimeMillis());
                
                for (int index = 0; index < jsonarray.length(); index++) {
                    JSONObject obj = (JSONObject) jsonarray.get(index);
                    if (null != obj) {
                        PushMsg pushMsg = new PushMsg();
                        pushMsg.id = obj.getString("id");
                        pushMsg.c = obj.getString("c");
                        
                        needList.add(pushMsg);
                        if(null!=lastId && lastId.equals(pushMsg.id)){
                            needList.clear();
                        }
                        
                        if(index==jsonarray.length()-1){
                            updateLastPushId(pushMsg.id);
                        }
                    }
                }
            } 
        } catch(Exception e) {
            
        }
        return needList;
    }

    // 获取锁
    private void acquireWakeLock(Context context) {
        if (mWakeLock == null) {
            PowerManager powerManager = (PowerManager) (context
                    .getSystemService(Context.POWER_SERVICE));
            mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            mWakeLock.setReferenceCounted(false);
            mWakeLock.acquire(60 * 1000);
        }
    }

    // 释放锁
    private void releaseWakeLock() {
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    private String getLastPushId() {
        return mSP.getString(KEY_LAST_ID, "");
    }
    
    private void updateLastPushId(String lastPushId) {
        if (TextUtils.isEmpty(lastPushId)) {
            mSP.edit().remove(KEY_LAST_ID).commit();
            return;
        }
        mSP.edit().putString(KEY_LAST_ID, lastPushId).commit();
    }
    
    private boolean needPush() {
        return mSP.getBoolean(KEY_AUTO_POST, true);
    }

    private void showNotification(PushMsg pushMsg) {
        if (pushMsg == null) {
            return;
        }
        
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
         
        
        /*if(isOlympicPush(pushMsg.id)){//等有了奥运push开关后再使用
            return;
        }*/
        
        int id = R.drawable.stat_download_icon;
        int resId = R.drawable.stat_download_icon;
        String contentTitle = "网易新闻";

        Notification notification = new Notification(resId, pushMsg.c,
                System.currentTimeMillis());

        mNotificationManager.cancel(id);// 先清理之前的消息

        Intent intent = getWhere(pushMsg.id);
        PendingIntent contentIntent = PendingIntent.getActivity(this, resId, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.defaults = Notification.DEFAULT_SOUND;
        notification.setLatestEventInfo(this, contentTitle, pushMsg.c, contentIntent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(id, notification);
    }

    private class PushMsg {
        String id;

        String c;
    }

    public static void startPush(Context context) {
        startPushDelayed(context, 0);
    }

    public static void startPushDelayed(Context context, int delayMillis) {
        Intent intent = new Intent(context, PushService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        if (delayMillis <= 0) {
            AlarmUtil.deleteAlarm(context, alarmIntent);
            context.startService(intent);
            return;
        }
        AlarmUtil.addAlarm(context, alarmIntent, delayMillis);
    }

    public static void cancelPush(Context context) {
        Intent intent = new Intent(context, PushService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmUtil.deleteAlarm(context, alarmIntent);
    }
    
    public static boolean needPush(Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return sp.getBoolean(KEY_AUTO_POST, true);
    }
}
